package top.tupobi.zing.network;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import top.tupobi.zing.network.exception.NoDataExceptionException;
import top.tupobi.zing.network.exception.ServerResponseException;


/**
 *
 */
public abstract class DefaultObserver<T> implements Observer<T> {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T response) {
        onSuccess(response);
        onFinish();
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) { // HTTP错误
            HttpException httpException = (HttpException) e;
            ResponseBody errorBody = httpException.response().errorBody();
            // 解析服务端错误( status!=200的情况 )
            if (null != errorBody) {
                String body = "";
                try {
                    body = errorBody.string();
                } catch (IOException ioe) {
                    onFail(ioe.toString());
                }
                try {
                    BasicResponse r = new Gson().fromJson(body, BasicResponse.class);
                    if (null == r) {
                        onFail("null");
                    } else {
                        onFail(r.getMsg());
                    }
                } catch (Exception ex) {
                    onException(ExceptionReason.PARSE_ERROR, ex.toString() + "\n" + body);
                }
            } else {
                onFail("errorBody is null");
            }
        } else if (e instanceof ConnectException || e instanceof UnknownHostException) {   //   连接错误
            onException(ExceptionReason.CONNECT_ERROR, e.getMessage());
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            onException(ExceptionReason.CONNECT_TIMEOUT, e.getMessage());
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {   //  解析错误
            onException(ExceptionReason.PARSE_ERROR, e.toString());
        } else if (e instanceof ServerResponseException) { // 业务错误, 服务端返回的错误
            onFail(e.getMessage());
        } else if (e instanceof NoDataExceptionException) { // 业务正确, 没有获取到数据
            onFail(e.getMessage());
            return;
        } else {
            onException(ExceptionReason.UNKNOWN_ERROR, e.getMessage());
        }
        onFinish();
    }

    @Override
    public void onComplete() {
    }

    /**
     * 请求成功
     *
     * @param response 服务器返回的数据
     */
    abstract public void onSuccess(T response);

    public void onFinish() {
    }

    /**
     * 服务器返回数据，但响应码不为200
     */
    public void onFail(String msg) {
        ToastUtils.showLong(msg);
    }

    /**
     * 请求异常
     *
     * @param reason
     */
    public void onException(ExceptionReason reason, String msg) {
        switch (reason) {
            case CONNECT_ERROR:
                ToastUtils.showLong("网络连接错误" + "\n" + msg);
                break;
            case CONNECT_TIMEOUT:
                ToastUtils.showLong("网络连接超时" + "\n" + msg);
                break;
            case BAD_NETWORK:
                ToastUtils.showLong("网络环境异常" + "\n" + msg);
                break;
            case PARSE_ERROR:
                ToastUtils.showLong("解析数据失败" + "\n" + msg);
                break;
            case UNKNOWN_ERROR:
            default:
                ToastUtils.showLong("出现未知错误" + "\n" + msg);
                break;
        }
    }

    /**
     * 请求网络失败原因
     */
    public enum ExceptionReason {
        /**
         * 解析数据失败
         */
        PARSE_ERROR,
        /**
         * 网络问题
         */
        BAD_NETWORK,
        /**
         * 连接错误
         */
        CONNECT_ERROR,
        /**
         * 连接超时
         */
        CONNECT_TIMEOUT,
        /**
         * 未知错误
         */
        UNKNOWN_ERROR,
    }
}